#!/usr/bin/env node
import { program } from 'commander'
import chalk from 'chalk'
import { resolve } from 'node:path'
import { loadConfig } from './config.js'
import { performExtract } from './extract.js'
import { performReplace } from './replace.js'

program
  .name('i18n-extract')
  .description('Vue i18n extract & replace with auto translate')
  .option('-s, --src <dir>', 'source dir')
  .option('-o, --out <file>', 'output json')
  .option('-r, --replace', 'auto replace to i18n function')
  .action(async (opts) => {
    const cfg = await loadConfig()
    const src = resolve(opts.src || cfg.src)
    const out = resolve(opts.out || cfg.out)
    const enOut = resolve(out.replace(/zh-CN\.json$/, 'en-US.json')) // 自动派生英文文件

    console.log(chalk.cyan('🔍  Scanning...'))
    const { newKeys } = await performExtract(src, out, cfg.ext, enOut)
    console.log(chalk.green(`✅  Extracted ${newKeys} new keys → ${out}`))

    if (opts.replace || cfg.replace.enable) {
      console.log(chalk.cyan('🔄  Replacing source...'))
      const n = await performReplace(src, cfg.replace)
      console.log(chalk.green(`✅  Replaced ${n} files`))
    } else {
      console.log(
        chalk.yellow(
          '\n💡  Tip: add --replace or set replace.enable=true in config'
        )
      )
    }
  })

program.parse()
